<template>
  <div>
    <el-card class="box-card">
      <!-- 增加按钮 -->
      <el-button
        type="primary"
        size="default"
        icon="Plus"
        @click="addTrademark"
      >
        添加品牌
      </el-button>
      <!-- 表格组件，展示已有数据 -->
      <el-table style="margin: 10px 0" border :data="trademarkArr">
        <el-table-column label="序号" width="80px" align="center" type="index">
          <!-- 默认展示数据用div -->
        </el-table-column>
        <el-table-column label="品牌名称" prop="tmName"></el-table-column>
        <el-table-column label="品牌logo">
          <template #="{ row }">
            <img
              :src="row.logoUrl"
              alt=""
              style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateTrademark(row)"
            ></el-button>

            <el-popconfirm
              :title="`确认删除${row.tmName}?`"
              width="250px"
              icon="Delete"
              @confirm="removeTradeMark(row.id)"
            >
              <template #reference>
                <el-button
                  type="primary"
                  size="small"
                  @click=""
                  icon="Delete"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器组件
    current-page：当前页码
    page-size:每页数据条数
    page-sizes:下拉菜单数据
    background:分页器背景按钮颜色
    layout:调整组件部件位置
    -->
      <el-pagination
        @current-change="changePageNo"
        @size-change="sizeChange"
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        :small="false"
        :disabled="false"
        :background="true"
        layout="prev, pager, next, jumper,->,total, sizes "
        :total="total"
        :page-count="pages"
      />
    </el-card>
    <!-- 对话框组件:添加修改业务的时候使用 -->
    <!-- 
    v-model:控制对话框显示与隐藏,true显示，false隐藏 
    title:设置左上角标题
  -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
      @close=""
    >
      <el-form
        style="width: 80%"
        :model="trademarkParams"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="品牌名称" label-width="80px" prop="tmName">
          <el-input
            v-model="trademarkParams.tmName"
            placeholder="请输入品牌名称"
            size="normal"
            clearable
            @change=""
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌logo" label-width="80px" prop="logoUrl">
          <!-- upload组件相关配置
          action:图片上传路径请求url，带有/api
          show-file-list：上传的文件列表
          -->
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="cancel">
          取消
        </el-button>
        <el-button type="primary" size="default" @click="confirm">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import type {
  Records,
  TradeMarkResponseData,
  TradeMark,
} from '@/apis/product/trademark/type.ts'
import { ref, onMounted, reactive, nextTick } from 'vue'
//引入请求函数
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from '@/apis/product/trademark/index'
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'

//当前页码
let pageNo = ref<number>(1)
//每一页多少数据
let limit = ref<number>(3)
//存储已有品牌数据总数
let total = ref<number>(0)
//有多少页
let pages = ref<number>(9)
//存储已有品牌的数据
let trademarkArr = ref<Records>([])
//控制对话框显示和隐藏
let dialogFormVisible = ref(false)
//定义手机新增品牌数据
let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: '',
})
//获取el-form的组件实例
let formRef = ref()

//气泡确认框确定按钮的回调
const removeTradeMark = async (id: number) => {
  //点击确定按钮删除已有品牌需求
  let res = await reqDeleteTrademark(id)
  if (res.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除品牌成功',
    })

    //再次获取已有品牌数据
    getHasTrademark()
    //如果当前trademarkArr已经删除完毕了，就返回上一页
    if (trademarkArr.value.length < 1) {
      pageNo.value - 1
    }
  } else {
    ElMessage({
      type: 'error',
      message: '删除品牌失败',
    })
  }
}

//上传成功之后的回调
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  //response:为post请求返回的数据
  response,
  // uploadFile
) => {
  trademarkParams.logoUrl = response.data
  //图片上传成功，清除对应图片校验结果
  formRef.value.clearValidate('logoUrl')
}

//上传文件之前的钩子
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/jpeg' ||
    rawFile.type == 'image/gif'
  ) {
    //上传的文件大小
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '文件大小应小于4M',
      })
      return false
    }
  } else {
    //上传的文件类型
    ElMessage({
      type: 'error',
      message: '文件格式必须为png,jpg,gif',
    })
    return false
  }
}

//对话框底部取消按钮
const cancel = () => {
  dialogFormVisible.value = false
}
//对话框底部确认按钮
const confirm = async () => {
  //发请求之前，校验整个表单
  //校验全部通过才会继续执行
  let result = await formRef.value.validate()
  console.log(result)

  let res: any = await reqAddOrUpdateTrademark(trademarkParams)
  if (res.code === 200) {
    //添加成功
    //关闭对话框
    dialogFormVisible.value = false
    //弹出信息
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改成功' : '添加成功',
    })
    //再次发请求获取全部数据
    //添加返回第一页，修改留在当前页
    pageNo.value = trademarkParams.id ? pageNo.value : 1
    getHasTrademark()
  } else {
    //添加失败
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? '修改失败' : '添加失败',
    })
    dialogFormVisible.value = false
  }
}

//添加品牌按钮的回调
const addTrademark = () => {
  //清空数据
  trademarkParams.id = 0
  trademarkParams.logoUrl = ''
  trademarkParams.tmName = ''
  //清理未通过的表单验证信息
  //第一种方法
  // formRef.value?.clearValidate('tmName')
  // formRef.value?.clearValidate('logoUrl')
  //第二种方法
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })

  //显示对话框
  dialogFormVisible.value = true
}

//修改已有品牌按钮的回调
const updateTrademark = (row: TradeMark) => {
  Object.assign(trademarkParams, row)
  // trademarkParams.id = row.id
  // trademarkParams.tmName = row.tmName
  // trademarkParams.logoUrl = row.logoUrl
  //显示对话框
  dialogFormVisible.value = true

  //清理未通过的表单验证信息
  //第一种方法
  // formRef.value?.clearValidate('tmName')
  // formRef.value?.clearValidate('logoUrl')
  //第二种方法
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
}

//当页码下拉菜单发生变化时，触发方法,回传数据返回当前页条数选项
const sizeChange = () => {
  //每一页数据量发生变化时，当前页码归一
  pageNo.value = 1
  getHasTrademark()
}

//分页器页码发生变化时触发,有回传数据
const changePageNo = () => {
  //当前页码发生变化的时候再次发送请求获取已有品牌数据展示
  getHasTrademark()
}

//获取已有品牌接口封装为一个函数：在任何情况下获取数据，调用函数即可
const getHasTrademark = async () => {
  let result: TradeMarkResponseData = await reqHasTrademark(
    pageNo.value,
    limit.value,
  )
  // console.log(result)
  if (result.code === 200) {
    //存储总个数
    total.value = result.data.total
    trademarkArr.value = result.data.records
    pages.value = result.data.pages
  }
}
//品牌自定义校验规则方法
const validatorTmName = (_rule: any, value: any, callback: any) => {
  //自定义校验规则
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('品牌名称大于等于两位'))
    // callback('品牌名称大于等于两位')
  }
}
const validatorlogoUrl = (_rule: any, value: any, callback: any) => {
  if (value) {
    callback()
  } else {
    callback(new Error('Logo图片务必上传'))
  }
}

//表单校验规则对象
const rules = {
  tmName: [
    //required:字段务必校验，
    //trigger:触发时机，[blur、change]
    //失去焦点时执行方法
    { required: true, trigger: 'blur', validator: validatorTmName },
  ],
  logoUrl: [{ required: true, trigger: 'blur', validator: validatorlogoUrl }],
}

//挂载完毕钩子，发一次请求，获取第一页
onMounted(() => {
  getHasTrademark()
})
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
